import { ctx } from "../../scenes";
import {
  restoreDrawingSurface,
  saveDrawingSurface,
  windowToCanvas
} from "../../utils";
// 装饰者模式能够在不改变对象自身的基础上，
// 在程序运行期间给对象动态地添加职责。
export function addMouseDownEvent(vm) {
  const evName = 'mousedown';
  const handlers = vm.$options[evName]
  if (!handlers) return;
  const ret = handlers.bind(vm);
  function wrap(ev) {
    const loc = windowToCanvas(ev.clientX, ev.clientY);
    ret(loc);
    ev.preventDefault();
    saveDrawingSurface(ctx);
    vm.$dragging = true;
  }
  vm.$eventMap.set(evName, wrap);
  ctx.canvas.addEventListener(evName, wrap);
}
export function addMouseMoveEvent(vm) {
  const evName = 'mousemove';
  const handlers = vm.$options[evName]
  if (!handlers) return;
  const ret = handlers.bind(vm);
  function wrap(ev) {
    if (vm.$dragging) {
      ev.preventDefault();
      const loc = windowToCanvas(ev.clientX, ev.clientY);
      restoreDrawingSurface(ctx);
      ret(loc);
      //  drawGuidewires(ctx, loc);
      //  if(guidewires) {
      //     drawGuidewires(loc.x, loc.y);
      //  }
    }
  }
  vm.$eventMap.set(evName, wrap);
  ctx.canvas.addEventListener(evName, wrap);
}
export function addMouseUpEvent(vm) {
  const evName = 'mouseup';
  const handlers = vm.$options[evName]
  if (!handlers) return;
  const ret = handlers.bind(vm);
  function wrap(ev) {
    ev.preventDefault();
    const loc = windowToCanvas(ev.clientX, ev.clientY);
    restoreDrawingSurface(ctx);
    ret(loc);
    vm.$dragging = false;
    //  drawGuidewires(ctx, loc);
    //  if(guidewires) {
    //     drawGuidewires(loc.x, loc.y);
    //  }

  }
  vm.$eventMap.set(evName, wrap);
  ctx.canvas.addEventListener(evName, wrap);
}
export function removeEvent(vm) {
  const keyUp = function (ev) {
    const { key } = ev;
    if (key === 'Escape') {
      for (let [key, value] of vm.$eventMap.entries()) {
        ctx.canvas.removeEventListener(key, value);
      }
    }
  };
  document.addEventListener('keyup', keyUp);
}